<script lang="ts" setup>
import { BasicColumn } from '../types'
import { formatCell } from '../hooks/useColumns'
import { PropType, computed } from 'vue'
import { cloneDeep } from 'lodash-es'

// defineOptions({ name: 'TableCell' })
const props = defineProps({
    column: {
        type: Object as PropType<BasicColumn<any>>,
        required: true
    },
    value: {
        type: Object as PropType<any>
    },
    index: {
        type: Number,
        required: true
    }
})
// 获取组件名称
const getComponentName = computed(() => {
    if (typeof props.column.component === 'string') {
        return props.column.component
    } else if (typeof props.column.component === 'object') {
        return props.column.component.is
    }
    return 'span'
})

// 获取组件属性
const getComponentProps = computed(() => {
    if (typeof props.column.component === 'string') {
        switch (props.column.component) {
            case 'el-image':
                return {
                    src: props.value[props.column.prop as string] ?? '',
                    previewSrcList: [props.value[props.column.prop as string]]
                }
            default:
                break
        }
    } else if (typeof props.column.component === 'object') {
        const { component } = props.column
        const newProps: any = {}
        for (const key in component.props) {
            if (Object.hasOwnProperty.call(component.props, key)) {
                if (typeof component.props[key] === 'function') {
                    newProps[key] = component.props[key](props.value)
                } else if (typeof component.props[key] === 'object') {
                    newProps[key] = component.props[key][props.value[props.column.prop as string]]
                } else {
                    newProps[key] = component.props[key]
                }
            }
        }

        return newProps
    }
    return {}
})
// 获取组件内容
const getComponentContent = computed(() => {
    const { value, column, index } = cloneDeep(props)

    return formatCell(value[column.prop as string] ?? '', column?.format || '', value, index)
})
</script>
<template>
  <!-- 自定义组件 -->
  <template v-if="column.component">
    <el-image
      v-if="getComponentName === 'el-image'"
      v-bind="getComponentProps"
      fit="cover"
      preview-teleported
    >
      <template #error>
        <div class="image-slot">
          <el-icon><Picture /></el-icon>
        </div>
      </template>
    </el-image>
    <component v-else :is="getComponentName" v-bind="getComponentProps">
      {{ getComponentContent }}
    </component>
  </template>
  <span v-else>{{ getComponentContent }}</span>
</template>
<style lang="scss" scoped>
  .el-image {
    width: 50px;
    height: 50px;
  }
</style>
